/*
 * Project Name: jmax
 * File Name: SocketClient.java
 * Copyright: Copyright(C) 1985-2015 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.hotel.protocol.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xdtech.hotel.util.RedisUtils;

/**
 * socket 客户端发送工具
 * 
 * @author max.zheng
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2015-4-2 下午3:59:28
 */
public class SocketClientUtils
{
	private static Log log = LogFactory.getLog(SocketClientUtils.class);
	
	public static String sendData(String sn,String ip, int port, String data)
	{
		Socket socket = new Socket();
		InputStream inputStream = null;
		OutputStream outputStream = null;
		String rs = "";
		try
		{
//			socket = new Socket(ip, port);
			socket.connect(new InetSocketAddress(ip, port), 1500);
			socket.setSoTimeout(2000);
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			
			log.info("ip="+ip+"发送内容："+data);
			PrintWriter  out = new PrintWriter(outputStream, true); 
			out.println(data);
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			rs = in.readLine();
		    log.info("ip="+ip+"反馈接受结果："+rs);
		}
		catch (IOException e)
		{
//			sendSuccess = false;
			rs = e.getMessage();
			log.error("socket send error",e);
		}
		finally
		{
			try
			{
				if (null != inputStream)
				{
					inputStream.close();
				}
				if (null != outputStream)
				{
					outputStream.close();
				}
				if (null != socket)
				{
					socket.close();
				}
			}
			catch (Exception ee)
			{
				ee.printStackTrace();
			}

		}
		return rs;
	}
	
	/**
	 * write string 2 a outputstream
	 * 
	 * @param str
	 *            to write string
	 * @param in
	 *            stream
	 * @throws IOException 
	 */
	public static void writeStr2Stream(String str, OutputStream out) throws IOException {
		try {
			// add buffered writer
			BufferedOutputStream writer = new BufferedOutputStream(out);

			// write
			writer.write(str.getBytes());
			
			writer.flush();
		} catch (IOException ex) {
			throw ex;
		}
	}

	/**
	 * read string from a inputstream
	 * 
	 * @param in
	 * @return
	 * @throws IOException 
	 */
	public static String readStrFromStream(InputStream in) throws IOException {
		//System.out.println(getNowTime() + " : start to read string from stream");
		StringBuffer result = new StringBuffer("");

		// build buffered reader
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));

		// read 1024 bytes per time
		char[] chars = new char[2048];
		int len;
		
		try {
			while ((len = reader.read(chars)) != -1) {
				// if the length of array is 1M
				if (2048 == len) {
					//then append all chars of the array
					result.append(chars);
//					System.out.println("readStrFromStream : " + result.toString());
				} 
				// if the length of array is less then 1M
				else {
					//then append the valid chars
					for (int i = 0; i < len; i++) {
						result.append(chars[i]);
						//System.out.println("readStrFromStream : " + result.toString());
					}
					break;
				}
			}

		} catch (IOException e) {
//			System.out.println(e);
			throw e;
		}
		//System.out.println("end reading string from stream");
		return result.toString();
	}
	
	public static String getNowTime()
	{
		return new Date().toString();
	}

	public static void main(String[] args)
	{
		new SocketClientUtils();
	}
}
